package com.yaorange.common.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;

import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/7/15
 */
@Slf4j
@Component
public class SmsUtils {

    @Value("${aliyun.access-key}")
    public String accessKey;
    @Value("${aliyun.access-secret}")
    public String accessSecret;
    @Value("${aliyun.sign-name}")
    public String signName;
    @Value("${aliyun.template-code}")
    public String templateCode;

    private static StaticCredentialProvider provider;

    @PostConstruct
    public void init() {
        provider = getStaticCredentialProvider();
    }

    public  void sendSms(String mobilePhone, String code) {
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(mobilePhone)
                .templateParam("{\"code\":\""+code+"\"}")
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
            log.debug("调用阿里云短信接口发送成功:{}",new Gson().toJson(resp));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
     /*   response.thenAccept(resp -> {
            log.debug("调用阿里云短信接口发送成功:{}",new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            log.debug(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }

    private  StaticCredentialProvider getStaticCredentialProvider() {
        StaticCredentialProvider provider = com.aliyun.auth.credentials.provider.StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(accessKey)
                .accessKeySecret(accessSecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());
        return provider;
    }
}
